package com.house365.arequest.error;

import android.text.TextUtils;

import com.google.gson.stream.MalformedJsonException;
import com.house365.arequest.BuildConfig;
import com.house365.arequest.exception.RequestFailException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

public class ErrorParse {
    public static ErrorType parseError(Throwable throwable) {
        ErrorType type = ErrorType.UNKNOW;
        if (throwable instanceof RequestFailException) {
            type = ErrorType.REQUEST_FAIL;
            type.msg = throwable.getMessage();
            type.code = ((RequestFailException) throwable).getCode();
        } else if (throwable instanceof ConnectException) {
            type = ErrorType.NETWORK;
        } else if (throwable instanceof IOException) {
            type = ErrorType.IOERROR;
            if (throwable.getCause() instanceof SocketTimeoutException) {
                type = ErrorType.TIME_OUT;
            } else if (throwable.getCause() instanceof UnknownHostException) {
                type = ErrorType.UNKNOW_HOST;
            }
        } else if (throwable instanceof HttpException) {
            //请求非200走到这里
            type = ErrorType.HTTP;
        } else if (throwable instanceof MalformedJsonException) {
            type = ErrorType.JSON;
        } else {
            if (BuildConfig.DEBUG && (type == ErrorType.UNKNOW || type == ErrorType.JSON)) {
                throwable.printStackTrace();
            }
        }
        return type;
    }
}
